import socket
import csv
import time


def connect(target_host, target_port):
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.connect((target_host, int(target_port)))

    return client

def login(client, username, password, package_size=1024):
    res = client.recv(package_size)
    print('recv in connect: %s' % res)
    client.send(username.encode())

    res = client.recv(package_size)
    print('recv : %s' % res)

    if b'password' not in res:
        return
    client.send(password.encode())
    # 登录成功判断（如返回 Welcome 等字符）
    res = client.recv(package_size)
    print(res)
    if b'success' in res:
        return True

def sendMsg(client, msg_list, delay=1):
    for msg in msg_list:
        client.send(msg['cmd'].encode())

        if msg['recv']:
            res = client.recv(msg['recv'])
            print('send: %s\nrecv: %s' % (msg['cmd'], res))
        else:

            time.sleep(delay)



    # 是否接受响应的数据并应答

def loadServerDataWithCsv(file_name, encoding='utf-8'):
    """
    从 csv 文件载入服务器配置
    example: (可以是xls等文件直接转csv)
    ip, port, username, password
    "127.0.0.1", "23", "test", "test123"
    :param file_name: 文件名
    :param encoding: 编码
    :return:
    """
    with open(file_name, mode='r', encoding=encoding) as f:
        reader = csv.reader(f)
        res = []
        for row in reader:
            # 可以在这里对载入数据进行处理
            res.append(row)
            print(row)
        return res[1:]

def batchExe(clients, msg_list):
    """
    批量执行指令（串行,如需并行可以使用多线程）
    :param clients: 已建立连接的客户端
    :param msg: 消息
    :return:
    """
    for client in clients:
        sendMsg(client, msg_list)

def batchLogin(server_data):
    clients = []
    for item in server_data:
        client = connect(item[0], item[1])
        if login(client, item[2], item[3]):
            clients.append(client)
    return clients


if __name__ == '__main__':

    server_data = loadServerDataWithCsv('data/server.csv')
    clients = batchLogin(server_data)
    msg_list = [{
        'cmd': 'test',
        'recv': 1024
    }, {
        'cmd': 'abcd',
        'recv': 0
    }, {
        'cmd': 'quit',
        'recv': None
    }]
    batchExe(clients, msg_list)
